import Vue from 'vue'
import Vuex from 'vuex'
import { loginAPI } from '../api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 存储数据
    token: localStorage.getItem('token') || ''
  },
  mutations: {
    // 修改数据
    setToken (state, token) {
      state.token = token
      // 将数据存入本地
      localStorage.setItem('token', token)
    }
  },
  actions: {
    // 完成axios请求
    async loginAction (store, val) {
      try {
        const res = await loginAPI(val)
        console.log(res)
        const { token } = res.data.body
        console.log(token)
        store.commit('setToken', token)
        // 返回成功res对象
        return Promise.resolve(res)
      } catch (error) {
        // 返回失败res对象
        return Promise.reject(error)
      }
    }
  },
  modules: {
  }
})
